package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 1366. 通过投票对团队排名
 *
 * @author liw
 * @version 1.0
 * @date 2022/3/15 15:31
 */
public class RankTeams {
    public static void main(String[] args) {
        RankTeams test = new RankTeams();

        // ACB
        String[] arr = {"ABC", "ACB", "ABC", "ACB", "ACB"};

        // XWYZ
//        String[] arr =  {"WXYZ","XYZW"};

        // ZMNAGUEDSJYLBOPHRQICWFXTVK
//        String[] arr =  {"ZMNAGUEDSJYLBOPHRQICWFXTVK"};

        // ABC
//        String[] arr =  {"BCA","CAB","CBA","ABC","ACB","BAC"};

        // M
//        String[] arr = {"M","M","M","M"};

        String s = test.rankTeams(arr);
        System.out.println(s);
    }

    public String rankTeams(String[] votes) {
        int[][] arr = new int[26][27];
        for (int i = 0; i < 26; i++) {
            arr[i][26] = i;
        }
        int m = votes.length;
        int n = votes[0].length();
        for (int i = 0; i < m; i++) {
            String vote = votes[i];
            for (int j = 0; j < n; j++) {
                arr[vote.charAt(j) - 'A'][j]++;
            }
        }
        Arrays.sort(arr, (a, b) -> {
            for (int i = 0; i < 26; i++) {
                if (a[i] != b[i]) {
                    return Integer.compare(a[i], b[i]);
                }
            }
            return Integer.compare(b[26], a[26]);
        });
        int index = 0;
        a:
        for (int i = 0; i < 26; i++) {
            for (int j = 0; j < 26; j++) {
                if (arr[i][j] != 0) {
                    index = i;
                    break a;
                }
            }
        }
        char[] items = new char[26 - index];
        int j = 0;
        for (int i = 25; i >= index; i--) {
            items[j++] = (char) (arr[i][26] + 'A');
        }
        return String.valueOf(items);
    }

}
